package com.service.impl;

import com.dao.QueryPageDao;
import com.dao.ReaderDao;
import com.entity.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
//1
@Service
public class ReaderServiceImpl implements com.service.ReaderService {

    @Autowired
    QueryPageDao queryPageDao;

    @Autowired
    ReaderDao readerDao;

//    书籍信息查询
    @Override
    public PageResult queryPage(QueryPageBean queryPageBean, HttpServletRequest request) {
//        得到查询条件
        Integer currentPage=queryPageBean.getCurrentPage();
        Integer pageSize=queryPageBean.getPageSize();
        QueryPageBean.QueryString queryString=queryPageBean.getQueryString();
        String bNo=queryString.getbNo();
        String bName=queryString.getbName();
        String author=queryString.getAuthor();
        String bTypeName=queryString.getbTypeName();
        //通过类型名查询类型编号
        Integer bTypeNo=queryPageDao.queryTypeNo(bTypeName);

        //查询条件放入map
        Map<String,Object> queryMap=new HashMap<>();
        queryMap.put("bNo",bNo);
        queryMap.put("bName",bName);
        queryMap.put("author",author);
        queryMap.put("bTypeNo",bTypeNo);

        //分页查询
        PageHelper.startPage(currentPage,pageSize);
//        System.out.println(pageSize);
//        System.out.println(currentPage);
        Page page=queryPageDao.queryPage(queryMap);

//        查询到的图书集合
        List<Books> rows=page.getResult();
        long total=page.getTotal();
        //获得最大借阅时长
        HttpSession session=request.getSession();

////        session中得到用户信息
        User user= (User) session.getAttribute("user");
////        根据用户类型查询权限
        Integer rTypeNo=user.getrTypeNo();


//        Integer rTypeNo=1;

        Reader reader =readerDao.queryPower(rTypeNo);
        Integer brDay=reader.getBrDay();

//      赋予最大借阅时长
        for (Books book:rows){
            book.setBrDay(brDay);
            System.out.println(book);
        }

        PageResult pageResult=new PageResult(total,rows);

        return pageResult;
    }
    //借书
    @Override
    public void borrowBook(Integer bNo, Integer brDay, HttpServletRequest request) {


        HttpSession session=request.getSession();
////      session中得到用户信息
        User user= (User) session.getAttribute("user");
////        根据用户类型查询权限
        Integer uNo=user.getuNo();
        Integer rTypeNo=user.getrTypeNo();

//        Integer uNo=1;
//        Integer rTypeNo=1;

        Map<String,Object> map=new HashMap<>();
        map.put("rTypeNo",rTypeNo);
        map.put("uNo",uNo);
        map.put("bNo",bNo);

        //查询可借阅册数
        Integer brNo=readerDao.queryBrNo(map);
        //查询已借册数
        Integer hasBorrow=readerDao.queryHasBorrow(uNo);
        //查询可借阅天数
        Integer ubrDay=readerDao.queryBrDay(rTypeNo);
        //查询在管册数
        Integer eNumber=readerDao.queryENumber(bNo);

        //验证是否满足借阅条件
        if(ubrDay>=brDay && brNo>hasBorrow && eNumber>0){
            //可借阅天数>=借阅天数;可借阅册数>已借册数;在管册数>0

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar=Calendar.getInstance();
            Date nowDate=new Date();

            //得到借书时间
            String brTime=sdf.format(nowDate);

            calendar.setTime(nowDate);
            calendar.add(Calendar.DATE,brDay);
            //计算预预期还书时间
            String exceptReturn=sdf.format(calendar.getTime());

            map.put("brTime",brTime);
            map.put("exceptReturn",exceptReturn);

            //查询是否以前借过这书
            int flag=readerDao.queryHadBorrow(bNo,uNo);
            if(flag==1){
                readerDao.updateBorrowed(map);
//                System.out.println("yes");
            }else{
                //借书
                readerDao.borrowBook(map);
            }


            //修改图书在管数-1
            readerDao.updateENumber(bNo,eNumber-1);
        }else{

            throw new RuntimeException();
        }
    }



    //还书信息查询
    @Override
    public PageResult getBorrowBooks(QueryPageBean queryPageBean, HttpServletRequest request) {
//        得到查询条件
        Integer currentPage=queryPageBean.getCurrentPage();
        Integer pageSize=queryPageBean.getPageSize();
        QueryPageBean.QueryString queryString=queryPageBean.getQueryString();
        String bNo=queryString.getbNo();
        String bName=queryString.getbName();
        String author=queryString.getAuthor();
        String bTypeName=queryString.getbTypeName();

//        通过session得到用户信息
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute("user");
        Integer uNo=user.getuNo();
//        Integer uNo=1;

        //查询条件放入map
        Map<String,Object> queryMap=new HashMap<>();
        queryMap.put("uNo",uNo);
        queryMap.put("bNo",bNo);
        queryMap.put("bName",bName);
        queryMap.put("author",author);
        queryMap.put("bTypeName",bTypeName);
//        System.out.println(queryMap);

        //分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page page=readerDao.queryBorrowBooks(queryMap);

        //        查询到的未还图书集合
        List<BorrowBooks> rows=page.getResult();
        long total=rows.size();

//        计算未还书籍的剩余时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar=Calendar.getInstance();
        for(BorrowBooks borrowBook:rows){
//            System.out.println(borrowBook);
            //得到借书日期
//            String brTime= borrowBook.getBrTime();
            //得到预期还书日期
            String exceptionReturn=borrowBook.getExpectReturn();
//            System.out.println(brTime);
            try {
//                calendar.setTime(sdf.parse(brTime));
//                int brDays=calendar.get(Calendar.DAY_OF_YEAR);

                calendar.setTime(sdf.parse(exceptionReturn));
                int exceptionReturnDays=calendar.get(Calendar.DAY_OF_YEAR);

                calendar.setTime(new Date());
                int nowDays=calendar.get(Calendar.DAY_OF_YEAR);

                //计算剩余时间
                int remindTime=exceptionReturnDays-nowDays;
                //设置剩余时间
                borrowBook.setRemindTime(remindTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
//            System.out.println(borrowBook);
        }


        PageResult pageResult=new PageResult(total,rows);

        return pageResult;
    }
    //还书
    @Override
    public void returnBook(Integer bNo, HttpServletRequest request) {
        //        通过session得到用户信息
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute("user");
        Integer uNo=user.getuNo();
//        Integer uNo=1;

        Map<String,Object> map=new HashMap<>();
        map.put("uNo",uNo);
        map.put("bNo",bNo);
        //得到要还的书
        BorrowBooks borrowBooks=readerDao.queryBorrowBooks2(map);

        //得到还书日期（今天）
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String returnTime=sdf.format(new Date());

        //还书
        map.put("returnTime",returnTime);
        readerDao.returnBook(map);
//        System.out.println(returnTime);
    }


    //    书籍借阅信息查询
    @Override
    public PageResult getBorrowDetail(QueryPageBean queryPageBean, HttpServletRequest request) {
        //        得到查询条件
        Integer currentPage=queryPageBean.getCurrentPage();
        Integer pageSize=queryPageBean.getPageSize();
        QueryPageBean.QueryString queryString=queryPageBean.getQueryString();
        String bNo=queryString.getbNo();
        String bName=queryString.getbName();
        String author=queryString.getAuthor();
        String bTypeName=queryString.getbTypeName();


//        通过session得到用户信息
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute("user");
        Integer uNo=user.getuNo();
//        Integer uNo=1;

        //查询条件放入map
        Map<String,Object> queryMap=new HashMap<>();
        queryMap.put("uNo",uNo);
        queryMap.put("bNo",bNo);
        queryMap.put("bName",bName);
        queryMap.put("author",author);
        queryMap.put("bTypeName",bTypeName);
//        System.out.println(queryMap);

        //分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page page=readerDao.queryBorrowDetail(queryMap);

        //        查询到的借阅图书集合
        List<BorrowBooks> rows=page.getResult();
        long total=rows.size();

        PageResult pageResult=new PageResult(total,rows);

        return pageResult;
    }
    //续借
    @Override
    public void borrowAgain(Integer bNo,HttpServletRequest request) {
        //        通过session得到用户信息
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute("user");
        Integer uNo=user.getuNo();
        Integer rTypeNo=user.getrTypeNo();
//        Integer uNo=1;
//        Integer rTypeNo=1;

        //查询可续借次数
        int brNum=readerDao.queryBrNum(rTypeNo);
        //查询可借天数
        int brDay=readerDao.queryBrDay(rTypeNo);
//        System.out.println(brNum);

        Map<String,Object> map=new HashMap<>();
        map.put("uNo",uNo);
        map.put("bNo",bNo);
        //得到要续借的书籍
        BorrowBooks borrowBooks=readerDao.queryBorrowBooks2(map);

        //        计算未还书籍的剩余时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar=Calendar.getInstance();
        int remindTime = 0;
        try {
            calendar.setTime(sdf.parse(borrowBooks.getExpectReturn()));
            int exceptionReturnDays=calendar.get(Calendar.DAY_OF_YEAR);

            calendar.setTime(new Date());
            int nowDays=calendar.get(Calendar.DAY_OF_YEAR);

            //计算剩余时间
            remindTime=exceptionReturnDays-nowDays;
            //设置剩余时间
            borrowBooks.setRemindTime(remindTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if((brNum>borrowBooks.getBrNum())&&(remindTime<brDay-10)){
            //未达到续借上限且续借后不会超过最大借阅天数

            String exceptReturn=borrowBooks.getExpectReturn();

            try {
                calendar.setTime(sdf.parse(exceptReturn));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //计算续借10天后的预期归还日期
            calendar.add(Calendar.DATE,10);
            String exceptReturn2=sdf.format(calendar.getTime());

            //修改借阅信息
            map.put("brNum",borrowBooks.getBrNum()+1);
            map.put("exceptReturn",exceptReturn2);
            readerDao.updateBorrow(map);
        }else{
            //达到续借上限
            throw new RuntimeException();
        }



    }



}
